from app import db, bcrypt
from datetime import datetime

class Admin(db.Model):
    
    """管理员模型"""
    __tablename__ = 'admins'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False, comment='用户名')
    password_hash = db.Column(db.String(255), nullable=False, comment='密码哈希')
    real_name = db.Column(db.String(50), comment='真实姓名')
    role = db.Column(db.Enum('super_admin', 'admin', 'editor'), default='editor', comment='角色')
    is_active = db.Column(db.Boolean, default=True, comment='是否激活')
    last_login_at = db.Column(db.DateTime, comment='最后登录时间')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    articles = db.relationship('Article', backref='creator', lazy='dynamic')
    questions = db.relationship('Question', backref='creator', lazy='dynamic')
    exams = db.relationship('Exam', backref='creator', lazy='dynamic')
    operation_logs = db.relationship('OperationLog', backref='admin', lazy='dynamic')
    
    def __repr__(self):
        return f'<Admin {self.username}>'
    
    def set_password(self, password):
        """设置密码"""
        self.password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
    
    def check_password(self, password):
        print( 'password:' + bcrypt.generate_password_hash(password).decode('utf-8') )
        
        """验证密码"""
        return bcrypt.check_password_hash(self.password_hash, password)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'username': self.username,
            'real_name': self.real_name,
            'role': self.role,
            'is_active': self.is_active,
            'last_login_at': self.last_login_at.isoformat() if self.last_login_at else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    @property
    def is_super_admin(self):
        """是否为超级管理员"""
        return self.role == 'super_admin'
    
    @property
    def is_admin(self):
        """是否为管理员"""
        return self.role in ['super_admin', 'admin'] 